//
//  RouteImageTableCell.m
//  Cycling
//
//  Created by 迟国强 on 2023/4/5.
//

#import "RouteImageTableCell.h"
#import "ImageItemCell.h"

@interface RouteImageTableCell ()

@property (weak, nonatomic) IBOutlet UILabel *imageNumsLbl;

@end

@implementation RouteImageTableCell

- (void)awakeFromNib {
    [super awakeFromNib];
    [self.collectionView registerNib:[UINib nibWithNibName:@"ImageItemCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ImageItemCell"];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}
#pragma mark

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    ImageItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageItemCell" forIndexPath:indexPath];
    
    if(self.editModel.images.count <= indexPath.row) {
        cell.defaultImageName = @"cycling_detail_add_image_icon";
    } else {
        cell.iconImage = [self.editModel.images objectAtIndex:indexPath.row];
    }
    cell.imageIndex = indexPath.row;
    cell.deleteButtonBlock = ^(NSInteger imageIndex) {
        if(self.editModel.images.count > imageIndex) {
            [self.editModel.images removeObjectAtIndex:imageIndex];
        }
        [self.collectionView reloadData];
        [self reloadImageNumsLbl];
    };
    
    return cell;
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return MIN(self.editModel.images.count + 1, 10);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(100, 100);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.editModel.images.count <= indexPath.row) {
        if(self.willAddImageBlock) {
            self.willAddImageBlock();
        }
        return;
    }
}

- (void)setEditModel:(CyclingRouteEditModel *)editModel
{
    _editModel = editModel;
    [self.collectionView reloadData];
    [self reloadImageNumsLbl];
}

- (void)reloadImageNumsLbl
{
    self.imageNumsLbl.text = [NSString stringWithFormat:@"%@/10", @(self.editModel.images.count)];
}

@end
